package com.shimao.celnet.payment.service.impl;

import com.github.pagehelper.PageHelper;
import com.shimao.celnet.payment.form.ASysUserForm;
import com.shimao.celnet.payment.form.SelectTree;
import com.shimao.celnet.payment.mapper.ASysRoleMapper;
import com.shimao.celnet.payment.mapper.ASysUserRoleMapper;
import com.shimao.celnet.payment.model.ASysRole;
import com.shimao.celnet.payment.model.ASysUser;
import com.shimao.celnet.payment.model.ASysUserRole;
import com.shimao.celnet.payment.service.ASysUserService;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ensure on 2017/4/21.
 */
@Service
public class ASysUserServiceImpl extends BaseServiceImpl<ASysUser> implements ASysUserService {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired(required = false)
    private ASysUserRoleMapper aSysUserRoleMapper;

    @Autowired(required = false)
    private ASysRoleMapper aSysRoleMapper;
    /**
     * 分页查询
     * @param formBean
     * @param pageNum
     * @param length
     * @return
     */
    @Override
    public ASysUserForm getByPage(ASysUserForm formBean, int pageNum, int length) {

        Example example = new Example(ASysUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(formBean.getUserName())) {
            criteria.andLike("userName", "%" + formBean.getUserName() + "%");
        }
        if (StringUtil.isNotEmpty(formBean.getPhone())) {
            criteria.andLike("phone", "%"+formBean.getPhone()+"%");
        }
        if (StringUtil.isNotEmpty(formBean.getRealName())) {
            criteria.andLike("realName", "%"+formBean.getRealName()+"%");
        }
        if (StringUtil.isNotEmpty(formBean.getUnit())) {
            criteria.andLike("unit", "%"+formBean.getUnit()+"%");
        }
        //分页查询
        PageHelper.startPage(pageNum, length);
        List<ASysUser> userList = mapper.selectByExample(example);
        formBean.setPageInfo(userList);

        return  formBean;
    }

    /**
     * 保存用户，用户角色信息
     * @param aSysUser
     * @param roleGuidMap 用户角色Guid  list
     */
    @Override
    @CacheEvict(cacheNames="users", allEntries=true)
    @Transactional(propagation= Propagation.REQUIRES_NEW,readOnly=false,rollbackFor={Exception.class})
    public int save(ASysUser aSysUser,Map<String, String> roleGuidMap) {
        logger.info("保存用户，用户角色信息--开始");
        String loginUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        aSysUser.setGuid(getGuid());
        aSysUser.setUpdateUserGuid(loginUserGuid);
        aSysUser.setCreatedUserGuid(loginUserGuid);
        //保存角色
        int retCnt = save(aSysUser);
        logger.debug("保存用户信息");

        //更新用户相关角色
        updateRolePermission(loginUserGuid,aSysUser.getGuid(),roleGuidMap);

        logger.info("保存用户，用户角色信息--结束");
        return retCnt;
    }

    /**
     * 修改用户，用户角色信息
     * @param aSysUser
     * @param roleGuidMap 用户角色Guid  list
     */
    @Override
    @CacheEvict(cacheNames="users", allEntries=true)
    @Transactional(propagation= Propagation.REQUIRES_NEW ,readOnly=false,rollbackFor={Exception.class})
    public int update(ASysUser aSysUser, Map<String, String> roleGuidMap) {
        logger.info("修改：用户，用户角色信息--开始");
        String loginUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        aSysUser.setUpdateUserGuid(loginUserGuid);

        logger.debug("修改：用户");
        int retCnt =  update(aSysUser);

        //更新用户相关角色
        updateRolePermission(loginUserGuid,aSysUser.getGuid(),roleGuidMap);

        logger.info("修改：用户，用户角色信息--结束");
        return retCnt;
    }


    /**
     * 用户信息删除，用户角色信息删除
     * @param userGuid
     * @return
     */
    @CacheEvict(cacheNames="users", allEntries=true)
    @Transactional(propagation= Propagation.REQUIRES_NEW,readOnly=false,rollbackFor={Exception.class})
    public int delete(String userGuid) {
        //删除用户表
        int delCnt=mapper.deleteByPrimaryKey(userGuid);

        //删除用户角色表
        aSysUserRoleMapper.deleteByUser(userGuid);
        return delCnt;
    }

    /**
     * 根据用户名称，用户信息
     * @param userName
     */
    public ASysUser  getByUsername(String userName){

        Example example = new Example(ASysUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userName", userName);

        List<ASysUser> userList = mapper.selectByExample(example);
        if(userList.size()>0){
            return userList.get(0);
        }else{
            return new ASysUser();
        }

    }

    /**
     * 角色生成
     * @param userGuid
     * @return
     */
    public  List<SelectTree>  creatRoleTree(String userGuid) {
        Map<String, String> guidMap = new HashMap<String, String>();
        if(StringUtils.isNotEmpty(userGuid)){
            //角色对应权限取得
            List<ASysRole> aSysRoleLs= aSysRoleMapper.selectRoleByUser(userGuid);
            for(ASysRole aSysRole:aSysRoleLs){
                guidMap.put(aSysRole.getGuid(),aSysRole.getGuid());
            }
        }

        List<ASysRole> aSysRoleAll = aSysRoleMapper.selectAll();
        List<SelectTree> retTreeList = new ArrayList<SelectTree>();
        for(ASysRole role:aSysRoleAll){
            SelectTree selectTree = new SelectTree();
            selectTree.setGuid(role.getGuid());//节点value
            selectTree.setDataSection(FinalUtil.ROLE_ROOT);//父级名称
            selectTree.setOptionText(role.getRoleName());//树节点名称
            selectTree.setStrSelected(FinalUtil.DISABLE);//无权限
            if(StringUtils.isNotEmpty(guidMap.get(role.getGuid()))) {
                selectTree.setStrSelected(FinalUtil.ENABLE);//有权限
            }
            retTreeList.add(selectTree);

        }
        return retTreeList;
    }

    /**
     * 保存用户角色信息
     * @param userGuid
     * @param roleGuidMap 角色Guid  list
     */
    public int  updateRolePermission(String loginUserGuid,String userGuid,Map<String, String> roleGuidMap) {
        logger.debug("修改：用户角色信息--开始");
        int retCnt=0;
        aSysUserRoleMapper.deleteByUser(userGuid);
        for (String roleGuid : roleGuidMap.keySet()) {
            ASysUserRole userRole = new ASysUserRole();
            userRole.setGuid(aSysUserRoleMapper.selectGuid());
            userRole.setRoleGuid(roleGuid);
            userRole.setUserGuid(userGuid);
            userRole.setUpdateUserGuid(loginUserGuid);
            userRole.setCreatedUserGuid(loginUserGuid);
            aSysUserRoleMapper.insert(userRole);
        }

        logger.debug("修改：用户角色信息--结束");
        return retCnt;
    }
}
